<template>
  <q-layout view="hHh lpR fFf">

    <q-header elevated class="bg-primary text-white" height-hint="98">
      <q-toolbar>
        <q-btn dense flat round icon="menu" @click="left = !left"/>
        <q-btn dense flat round icon="home" @click="backHome"></q-btn>

        <q-toolbar-title>
          Financial Report Viewer
        </q-toolbar-title>
        <q-btn dense flat round icon="menu" @click="right = !right"/>

        <!--        <q-input bottom-slots v-model="codeText" rounded outlined hide-bottom-space-->
        <!--                 placeholder="输入证券代码或简称" :dense="true" color="lime-11" bg-color="white">-->
        <!--          <template v-slot:append>-->
        <!--            <q-icon v-if="codeText !== ''" name="close" @click="codeText = ''" class="cursor-pointer"/>-->
        <!--            <q-icon name="search"/>-->
        <!--          </template>-->
        <!--        </q-input>-->
      </q-toolbar>
      <!--      <div class="fit row justify-end items-end  q-gutter-md">-->
      <!--        <q-select v-model="yearChoose" :options="yearOptions" bg-color="white" label="年度" rounded-->
      <!--                  class="q-ma-sm q-pt-md " style="min-width: 150px" dense/>-->
      <!--        <q-select v-model="typeChoose" :options="typeOptions" bg-color="white" label="公告类型" rounded-->
      <!--                  class="q-ma-sm q-pd-md" style="min-width: 150px" dense/>-->
      <!--      </div>-->
    </q-header>

    <q-drawer show-if-above v-model="left" side="left" :width="drawWidth" bordered>
      <q-splitter
          v-model="splitterModel"
          horizontal
          style="height: 100%;"
      >
        <template v-slot:before>
          <div class="text-h4 q-mb-md">目录</div>
          <div class="la-align-left">
            <q-scroll-area style="height: 600px; max-width: 100%;" class="bg-grey-1 rounded-borders">
              <p v-html="Outline" class="la-align-left"></p>
            </q-scroll-area>
          </div>
        </template>

        <template v-slot:after>
          <div style="min-height: 300px">
            <q-tabs
                v-model="tab"
                class="text-blue-5"
                no-caps
                draggable="false"
            >
              <q-tab name="history" icon="hourglass_full" label="历年比较"/>
              <q-tab name="entity" icon="store" label="实体"/>
              <q-tab name="search" icon="search" label="外部检索"/>
            </q-tabs>

            <q-tab-panels
                v-model="tab"
                animated
                vertical
                transition-prev="jump-up"
                transition-next="jump-up"
            >

              <q-tab-panel name="history">
                <div class="text-h4 q-mb-md">
                  <div>历史报告对比</div>
                </div>
                <report-history :selectStr="selectStr"  v-if="showHistory" :announcementEmotion="announcementEmotion"
                                :recentAnnouncementInfo="recentAnnouncementInfo"></report-history>
              </q-tab-panel>

              <q-tab-panel name="entity">
                <div class="text-h4 q-mb-md">查看所有实体</div>
                <report-entity :selectedEntity.sync="searchText"></report-entity>
              </q-tab-panel>


              <q-tab-panel name="search">
                <report-search :searchText="searchText"></report-search>
              </q-tab-panel>


            </q-tab-panels>
          </div>
        </template>
      </q-splitter>
    </q-drawer>

    <q-page-container>
      <q-page class="q-pa-sm">
        <div class="column" style="width: 100%">
          <!--                    <q-card class="col report-card q-ma-sm q-pa-sm" align="center">-->
          <!--                        <div class="text-h6">{{reportTitle}}</div>-->
          <!--                    </q-card>-->


          <!--                    <q-card v-for="n in flatText.length" :key="n" class="col report-card q-pa-xs" align="left" flat-->
          <!--                            style="text-indent: 2ch;" v-ripple="false">-->

          <!--                        <div class="text-body2"-->
          <!--                             :style="'width: 100%;cursor: pointer;border-right: 2px solid '-->
          <!--                             + colorBand[Math.floor(Math.random()*colorBand.length)]"-->
          <!--                             v-ripple @click="selectReportStr">-->
          <!--                            {{flatText[n]}}-->
          <!--                        </div>-->
          <!--                    </q-card>-->
          <q-no-ssr v-if="forceRander">
            <p ref="htstr" v-html="reportContent"></p>
          </q-no-ssr>
          <q-spinner-gears size="50px" color="primary" v-if="visible" class="absolute-center"/>

        </div>
      </q-page>
    </q-page-container>

    <q-drawer show-if-above v-model="right" side="right" :width="drawWidth" bordered>
      <q-splitter
          v-model="splitterModelRight"
          horizontal
          style="height: 100%"
      >
        <template v-slot:before>
          <!--          <q-card class="my-card col-3 caption" :id="companyInfo.code" align="left">-->

          <q-card-section>
            <div class="text-h6">{{ announcementInfo.announcementTitle }}</div>
            <div class="text-subtitle2 text-primary">报告日期:{{ announcementInfo.announcementTime }}
            </div>
            <div class="text-subtitle2 text-accent" v-if="showHistory">
              <q-icon name="face"></q-icon>
              情绪评级:{{ announcementEmotion[$route.query.announcementId] }}
            </div>
          </q-card-section>
          <q-separator inset/>
          <q-card-section>
            <div class="text-h6">{{ companyInfo.full_name }}</div>
            <div class="text-subtitle2 text-primary">
              代码:{{ companyInfo.a_code || companyInfo.b_code || companyInfo.c_code }}
              <span class="text-body2 text-grey"> | {{ companyInfo.industry_1 }}</span>
              <span class="text-body2 text-grey"> | {{ companyInfo.industry_2 }}</span>
              <span class="text-body2 text-grey"> | {{ companyInfo.province }}</span>
              <span class="text-body2 text-grey"> | {{ companyInfo.city }}</span>
            </div>
          </q-card-section>
          <q-separator inset/>
          <q-card-section vertical align="left">
            <div class="text-body2 text-primary">注册资本<span class="text-body2 text-grey">：{{
                companyInfo.register_capital
              }} {{ companyInfo.currency }}</span>
            </div>
            <div class="text-body2 text-primary">联系方式<span class="text-body2 text-grey">：{{
                companyInfo.contact_number
              }}</span>
            </div>
            <div class="text-body2 text-primary">网址<span class="text-body2 text-grey">：{{ companyInfo.website }}</span>
            </div>
            <div class="text-body2 text-primary">电子邮箱<span class="text-body2 text-grey">：{{ companyInfo.email }}</span>
            </div>
            <div class="text-body2 text-primary">会计师事务所<span class="text-body2 text-grey">：{{
                companyInfo.cpafirm
              }}</span>
            </div>
            <div class="text-body2 text-primary">律师事务所<span class="text-body2 text-grey">：{{
                companyInfo.lawfirm
              }}</span>
            </div>
            <div class="text-body2 text-primary">主营业务<span
                class="text-body2 text-grey">：{{ companyInfo.main_business }}</span></div>
            <div class="text-body2 text-primary">业务范围<span
                class="text-body2 text-grey">：{{ companyInfo.business_scope }}</span></div>


          </q-card-section>
          <!--          </q-card>-->
        </template>

        <template v-slot:after>
          <charts security="000630.XSHE"></charts>
        </template>
      </q-splitter>
    </q-drawer>

    <q-footer elevated class="bg-white shadow-0" bordered style="height: 200px">
      <report-relation v-if="showRelation" :destCompany="companyInfo.full_name"></report-relation>
    </q-footer>
  </q-layout>
</template>

<script scoped>
// import reportIndex from "@/components/reportIndex";
// import reportEmotion from "@/components/reportEmotion";
import reportEntity from "@/components/reportEntity";
import reportSearch from "@/components/reportSearch";
import reportRelation from "@/components/reportRelation";
import reportHistory from "@/components/reportHistory";
import charts from "@/components/charts";

export default {
  name: "PdfViewPage",
  components: {
    reportRelation, reportEntity, reportSearch, reportHistory, charts,
    // reportIndex, reportEmotion,
  },
  watch: {
    searchText: function () {
      this.tab = "search"
    }
  },
  data() {
    return {
      left: true,
      right: true,
      showRelation: false,
      showHistory: false,
      tab: 'history',
      splitterModel: 50,
      splitterModelRight: 400,
      drawWidth: 350,
      codeText: '',
      selectStr: "",
      searchText: "",
      yearChoose: "2019",
      yearOptions: ['2016', '2017', '2018', '2019'],
      typeChoose: "年报",
      typeOptions: ['年报', '半年报', '一季报', '三季报'],
      reportTitle: "",
      reportContent: "",
      forceRander: true,
      visible: true,
      recentAnnouncementInfo: [],
      announcementEmotion: {},
      colorBand: [],
      companyInfo: {},
      announcementInfo: {},
      Outline: "该文档无法解析目录"

    }
  },
  computed: {
    flatText: function () {
      return walkTree(this.treeData)
    },
  },
  methods: {
    selectReportStr: function (e) {
      this.selectStr = e.target.innerText;
    },
    backHome: function () {
      if (this.$router.currentRoute.path !== '/') {
        this.$router.replace('/')
      }
    },
  },
  created: async function () {
    this.colorBand = getBarColors(['#00ff00', '#ffffff', '#ff0000']);
    let res = null

    res = await this.$api.report.getSecInfo(this.$route.query.security)
    res = res.data.data
    this.companyInfo = res
    this.showRelation = true

    res = await this.$api.report.getReportInfo(this.$route.query.announcementId)
    res = res.data.data
    this.announcementInfo = res

    res = await this.$api.report.getAllRecentReportAnnouncementInfo(this.$route.query.secCode)
    res = res.data.data
    this.recentAnnouncementInfo = res

    for(let o of this.recentAnnouncementInfo){
      this.announcementEmotion[o.announcementId] = Math.ceil(Math.random()*7)
    }
    this.showHistory = true



    res = await this.$api.report.getAnnouncementOutline(this.$route.query.announcementId)
    if (res.data.code == 1) {
      res = res.data.data
      this.Outline = res
    }

    this.visible = true;
    res = await this.$api.report.getReportContent(this.$route.query.announcementId);
    // let res = await this.$api.report.testTemplate();
    // let js_res = await this.$api.report.reportTemplateJs();
    // js_res = js_res.data.data
    this.reportContent = res['data']
    this.forceRander = false;
    this.$nextTick().then(() => {
      this.forceRander = true;
      this.visible = false;
    })
    //       .then(()=>{
    //     let regJs = get_js_str(this.reportContent)
    //     var ele = document.createElement("script")
    //     ele.innerHTML = regJs
    //     console.log(regJs)
    //     this.$refs.htstr.append(ele)
    //     var ele2 = document.createElement("script")
    //     ele2.innerHTML = js_res
    //     console.log(js_res)
    //     this.$refs.htstr.append(ele2)
    //   });

  },
}

// function get_js_str(resdata){
//   var regJs = "";
//   resdata.replaceAll(/<script.*?>([\s\S]+?)<\/script>/img,function(_,js){    //正则匹配出script中的内容
//     regJs = js
//   });
//   return regJs
// }

function walkTree(treeData) {

  var nodes = [treeData[0].text];
  if (treeData.length > 0) {
    var stack = [];
    for (i = treeData.length - 1; i >= 0; i--) {
      stack.push(treeData[i])
    }


    while (stack.length != 0) {
      var item = stack.pop();
      nodes.push(item.text);

      var children = item.children;
      for (var i = children.length - 1; i >= 0; i--)
        stack.push(children[i]);
    }
  }

  return nodes;

}

// rgb to hex
function rgbToHex(r, g, b) {
  var hex = ((r << 16) | (g << 8) | b).toString(16);
  return "#" + new Array(Math.abs(hex.length - 7)).join("0") + hex;
}

// hex to rgb
function hexToRgb(hex) {
  var rgb = [];
  for (var i = 1; i < 7; i += 2) {
    rgb.push(parseInt("0x" + hex.slice(i, i + 2)));
  }
  return rgb;
}

function gradient(startColor, endColor, step = 10) {
  // 将 hex 转换为rgb
  var sColor = hexToRgb(startColor),
      eColor = hexToRgb(endColor);

  // 计算R\G\B每一步的差值
  var rStep = (eColor[0] - sColor[0]) / step;
  let gStep = (eColor[1] - sColor[1]) / step;
  let bStep = (eColor[2] - sColor[2]) / step;

  var gradientColorArr = [];
  for (var i = 0; i < step; i++) {
    // 计算每一步的hex值
    gradientColorArr.push(rgbToHex(parseInt(rStep * i + sColor[0]), parseInt(gStep * i + sColor[1]), parseInt(bStep * i + sColor[2])));
  }
  return gradientColorArr;
}

function getBarColors(allColor) {
  let gradient_colors = [];
  for (let i = 0; i < allColor.length - 1; i++) {
    gradient_colors = gradient_colors.concat(gradient(allColor[i], allColor[i + 1], 10))
  }
  return gradient_colors;
}

</script>

<style lang="sass" scoped>
.report-card
  width: 100%
  max-width: 100%


</style>

<style type="text/css">
.l {
  text-decoration: none;
  color: #1D1D1D;
  text-align: left;
  float: inside;
  font-weight: bold;
  width: 100%;
  vertical-align: middle;
}

/*.ul {*/
/*  text-align: left;*/
/*  float:left;*/
/*}*/
</style>
